﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;
using System.Text;

using CE.User;
using CE.Global;
using CE.Database;
using CE.InputOut;
using CE.CarInsurance;
using CE.Mail;

public partial class carinsurance_offline_ApplicationStatus : System.Web.UI.Page
{

    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }

        if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
        {
            Response.Redirect("~/carinsurance/PendingApplication.aspx");
        }

        if (!IsPostBack)
        {
            lblError.Text = "";
            lblContent.Text = "";
            ddlDay1.Visible = true;
            lblFromDate.Text = Resources.General.Date + " : ";
            lblToDate.Visible = false;
            ddlDay2.Visible = false;
            ddlMonth2.Visible = false;
            ddlYear2.Visible = false;
            ddlYear1.Items.Clear();
            ddlYear2.Items.Clear();
            ddlTransYear.Items.Clear();
            int _cryr = dateTimeNow.Year;
            int _styr = 2012;
            for (int _year = _cryr; _year >= _styr; _year--)
            {
                ddlYear1.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
                ddlYear2.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
                ddlTransYear.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
            }

            ddlDay1.Text = dateTimeNow.Day.ToString("00");
            ddlMonth1.Text = dateTimeNow.Month.ToString("00");
            ddlYear1.Text = dateTimeNow.Year.ToString("0000");
            ddlDay2.Text = dateTimeNow.Day.ToString("00");
            ddlMonth2.Text = dateTimeNow.Month.ToString("00");
            ddlYear2.Text = dateTimeNow.Year.ToString("0000");

            if (Session[General.UserRole].ToString() == "100")
            {
                ddlReportType.Items.Clear();
                ddlReportType.Items.Add(new ListItem(Resources.General.Daily, "1"));

                ddlApplicationStatus.Items.Clear();
                ddlApplicationStatus.Items.Add(new ListItem(Resources.General.Pending, "0"));
            }
            if (Request.Params["search"] != null)
            {
                txtSearch.Text = Request.Params["search"].ToString();
                btnSubmit_Click(sender, e);
            }

            if (Session[General.UserRole].ToString() == "100")
            {
                btnPaymentReceiptDownload.Enabled = false;
                btnSendPaymentReceipt.Enabled = false;
                divSendPaymentReceipt.Visible = false;
            }

        }

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        lblError.Text = "";
        txtReportType.Text = ddlReportType.Text;
        txtAgentId.Text = Session[CE.Global.General.UserId].ToString();
        grvApplication.SelectedIndex = -1;
        grvApplication_SelectedIndexChanged(sender, e);
        divSearch.Visible = true;
        divSelectedApp.Visible = false;
        divSendPaymentReceipt.Visible = false;
        LoadGrid();
       
    }

    private void ClearFields()
    {
        lblMessage.Text = string.Empty;
        lblPaymentReceiptMessage.Text = string.Empty;
        lblQuoteRefNo.Text = string.Empty;
        lblPaymentStatus.Text = "0";
        lblSendToProviderStatus.Text = "0";
        lblPolicyIssuedStatus.Text = "0";
        lblMailingStatus.Text = "0";
        lblCompletedStatus.Text = "0";
        lblTransID.Text = "-1";
        lblTransID2.Text = "-1";
        lblTransID3.Text = "-1";
        lblCustomerID.Text = "-1";
        chkEmailEng.Checked = false;
        lblCarID.Text = "-1";
        lblProviderCompanyID.Text = "-1";

        chkStatus.Checked = true;
        txtRemark.Text = string.Empty;
        txtTrackingNumber.Text = "";
        txtTrackingRemark.Text = "ได้ทำการจัดส่ง กรมธรรม์ ให้ลูกค้าเรียบร้อยแล้วครับ";
        btnUpdateStatus.Enabled = false;
        UpdateStatusList();
    }

    protected void ddlReportType_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblError.Text = "";
        ddlDay1.Text = dateTimeNow.Day.ToString("00");
        ddlDay2.Text = dateTimeNow.Day.ToString("00");
        ddlMonth1.Text = dateTimeNow.Month.ToString("00");
        ddlMonth2.Text = dateTimeNow.Month.ToString("00");
        ddlYear1.Text = dateTimeNow.Year.ToString("0000");
        ddlYear2.Text = dateTimeNow.Year.ToString("0000");
        if (Convert.ToInt16(ddlReportType.Text) == 0)
        {
            ddlDay1.Visible = false;
            lblFromDate.Text = Resources.General.Date + " : ";
            lblToDate.Visible = false;
            ddlDay2.Visible = false;
            ddlMonth2.Visible = false;
            ddlYear2.Visible = false;
        }
        else if (Convert.ToInt16(ddlReportType.Text) == 1)
        {
            ddlDay1.Visible = true;
            lblFromDate.Text = Resources.General.Date + " : ";
            lblToDate.Visible = false;
            ddlDay2.Visible = false;
            ddlMonth2.Visible = false;
            ddlYear2.Visible = false;
        }
        else if (Convert.ToInt16(ddlReportType.Text) == 2)
        {
            lblFromDate.Text = " " + Resources.General.FromDate + " : ";
            lblToDate.Text = " " + Resources.General.ToDate + " : ";
            lblToDate.Visible = true;
            ddlDay2.Visible = true;
            ddlMonth2.Visible = true;
            ddlYear2.Visible = true;
            ddlDay1.Visible = true;
        }
    }

    protected void grvApplication_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblPromotionType.Text = "";
        ClearFields();
        if (grvApplication.SelectedIndex >= 0 && Session[General.UserRole].ToString() != "100")
        {
            DataKey _dataKey = grvApplication.SelectedDataKey;
            lblCarID.Text = _dataKey[0].ToString();
            lblCustomerID.Text = _dataKey[1].ToString();
            lblProviderCompanyID.Text = _dataKey[2].ToString();
            lblQuoteRefNo.Text = _dataKey[3].ToString();
            CheckApplicationStatus();
            LoadPaymentStatusGrid();
            LoadPaymentDetailList();
            LoadUploadDocument();
            GetCarDocumentDetails();
            LoadNonAppDetail();

            Int16 IsThai = GetCustomerType(lblCustomerID.Text);
            if (IsThai == 1)
                chkSendPaymentEng.Checked = false;
            else
                chkSendPaymentEng.Checked = true;

            GridViewRow _gvr = grvApplication.SelectedRow;

            if (_gvr.Cells[0].Text != string.Empty)
            {
                lblAppTypeDesc.Text = _gvr.Cells[0].Text.ToUpper();
            }

            if (_gvr.Cells[2].Text != string.Empty)
            {
                lblCustomerName.Text = _gvr.Cells[2].Text.ToUpper();
            }

            if (_gvr.Cells[3].Text != string.Empty)
            {
                lblCarPlate.Text = _gvr.Cells[3].Text.ToUpper();
            }

            if (_gvr.Cells[4].Text.ToString().ToLower() == "pending")
            {
                lblPaymentStatus.Text = "0";
                divSendPaymentReceipt.Visible = false;
            }
            else if (_gvr.Cells[4].Text.ToString().ToLower() == "nonpayment")
            {
                lblPaymentStatus.Text = "101";
                divSendPaymentReceipt.Visible = false;
            }
            else
            {
                lblPaymentStatus.Text = "1";
                divSendPaymentReceipt.Visible = true;
                ShowLastQuotationSendDate();
            }


            

            if (_gvr.Cells[5].Text.ToString().ToLower() == "no")
            {
                lblSendToProviderStatus.Text = "0";
            }
            else
            {
                lblSendToProviderStatus.Text = "1";
            }

           

            if (_gvr.Cells[6].Text.ToString().ToLower() == "no")
            {
                lblPolicyIssuedStatus.Text = "0";
            }
            else
            {
                lblPolicyIssuedStatus.Text = "1";
            }
            
            if (_gvr.Cells[7].Text.ToString().ToLower() == "no")
            {
                lblMailingStatus.Text = "0";
            }
            else
            {
                lblMailingStatus.Text = "1";
            }
            

            if (_gvr.Cells[8].Text.ToString().ToLower() == "no")
            {
                lblCompletedStatus.Text = "0";
            }
            else
            {
                lblCompletedStatus.Text = "1";
            }

            
            divSelectedApp.Visible = true;
            divUploadDocs.Visible = true;
            divPaymentStatus.Visible = true;
            divUpdateStatus.Visible = true;


            UpdateStatusList();
            divSearch.Visible = false;

           
            GetEmailLanguage();
        }
        else
        {
            LoadPaymentStatusGrid();
            LoadUploadDocument();
            GetCarDocumentDetails();
            divUploadDocs.Visible = false;
            divPaymentStatus.Visible = false;
            divUpdateStatus.Visible = false;
        }
    }
    
    private void UpdateStatusList()
    {
        ddlTransType.Items.Clear();
        int _selectItemValue = 0;

        if (lblPaymentStatus.Text == "1")
        {
            ddlTransType.Items.Add(new ListItem("Payment Completed", "100"));
            ddlTransType.Items.Add(new ListItem("Send To Provider", "200"));
            _selectItemValue = 200;
        }

        if (lblPaymentStatus.Text == "101")
        {
            ddlTransType.Items.Add(new ListItem("Payment Completed", "100"));
            ddlTransType.Items.Add(new ListItem("Non Payment Approval", "101"));
            ddlTransType.Items.Add(new ListItem("Send To Provider", "200"));
            _selectItemValue = 101;
        }

        // *** Old ***

        //if (lblSendToProviderStatus.Text == "1")
        //{
        //    ddlTransType.Items.Add(new ListItem("Policy Issued", "300"));
        //    _selectItemValue = 300;
        //}

        //if (lblPolicyIssuedStatus.Text == "1" && lblPaymentStatus.Text == "1")
        //{
        //    ddlTransType.Items.Add(new ListItem("Mailing Done", "400"));
        //    _selectItemValue = 400;
        //}
        //else if (lblPaymentStatus.Text == "101" && lblSendToProviderStatus.Text == "1" && lblPolicyIssuedStatus.Text == "1")
        //{
        //    ddlTransType.Items.Add(new ListItem("Mailing - Payment Pending", "0"));
        //    _selectItemValue = 0;
        //}

        //if (lblMailingStatus.Text == "1")
        //{
        //    ddlTransType.Items.Add(new ListItem("Closed/Completed", "1000"));
        //    _selectItemValue = 1000;
        //}

        // *** New ***

        if (lblSendToProviderStatus.Text == "1")
        {
            ddlTransType.Items.Add(new ListItem("Closed/Completed", "1000"));
            _selectItemValue = 1000;
        }

        // ***********

        if (ddlTransType.Items.Count > 0)
        {
            ddlTransType.Items.Insert(0, new ListItem("Select", "-1"));
            ddlTransType.Text = _selectItemValue.ToString();
            ddlTransType_SelectedIndexChanged(null, null);
        }
        else
        {
            if (lblQuoteRefNo.Text == string.Empty)
            {
                ddlTransType.Items.Insert(0, new ListItem("Select", "-1"));
                btnUpdateStatus.Enabled = false;
            }
            else
            {
                ddlTransType.Items.Add(new ListItem("Payment Completed", "100"));
                ddlTransType.Items.Add(new ListItem("Non Payment Approval", "101"));
                ddlTransType.SelectedIndex = 0;
                ddlTransType_SelectedIndexChanged(null, null);
            }
        }


    }

    public bool ValidDate(Int32 Year, Int32 Month, Int32 Day)
    {
        bool _isValid = true;
        int daysInMonth = 0;
        string leap, monthValid, dayValid, yearValid;
        if (Year >= 0000)
        {
            yearValid = "yes";
        }
        else
        {
            yearValid = "no";
        }
        if (Year % 400 == 0)
        {
            leap = "yes";
        }
        else if (Year % 100 == 0)
        {
            leap = "no";
        }
        else if (Year % 4 == 0)
        {
            leap = "yes";
        }
        else
        {
            leap = "no";
        }

        switch (Month)
        {
            case 1: daysInMonth = 31;
                break;
            case 3: daysInMonth = 31;
                break;
            case 4: daysInMonth = 30;
                break;
            case 5: daysInMonth = 31;
                break;
            case 6: daysInMonth = 30;
                break;
            case 7: daysInMonth = 31;
                break;
            case 8: daysInMonth = 31;
                break;
            case 9: daysInMonth = 30;
                break;
            case 10: daysInMonth = 31;
                break;
            case 11: daysInMonth = 30;
                break;
            case 12: daysInMonth = 31;
                break;
        }

        if (Month >= 1 && Month <= 12)
        {
            monthValid = "yes";
        }
        else
        {
            monthValid = "no";
        }
        if (Month == 2)
        {
            if (leap == "no")
            {
                daysInMonth = 28;
            }
            else if (leap == "yes")
            {
                daysInMonth = 29;
            }
        }

        if (1 <= Day && Day <= daysInMonth)
        {
            dayValid = "yes";
        }

        else
        {
            dayValid = "no";
        }

        if ((dayValid == "yes") && (monthValid == "yes") && (yearValid == "yes"))
        {
            _isValid = true;
        }
        else
        {
            _isValid = false;
        }

        return _isValid;
    }

    public string GetMonth(string month)
    {
        string result = "";
        if (month == "01")
        {
            result = " Jan ";
        }
        else if (month == "02")
        {
            result = " Feb ";
        }
        else if (month == "03")
        {
            result = " Mar ";
        }
        else if (month == "04")
        {
            result = " Apr ";
        }
        else if (month == "05")
        {
            result = " May ";
        }
        else if (month == "06")
        {
            result = " Jun ";
        }
        else if (month == "07")
        {
            result = " Jul ";
        }
        else if (month == "08")
        {
            result = " Aug ";
        }
        else if (month == "09")
        {
            result = " Sep ";
        }
        else if (month == "10")
        {
            result = " Oct ";
        }
        else if (month == "11")
        {
            result = " Nov ";
        }
        else if (month == "12")
        {
            result = " Dec ";
        }
        return result;
    }

    public bool Validatioin()
    {
        lblError.Text = "";
        bool _isValid = true;
        DateTime _fromDate, _toDate;
        if (Convert.ToInt16(ddlReportType.Text) == 1)
        {
            if (ddlDay1.SelectedIndex >= 0)
            {
                if (ValidDate(Convert.ToInt32(ddlYear1.Text), Convert.ToInt32(ddlMonth1.Text), Convert.ToInt32(ddlDay1.Text)))
                {
                    _fromDate = Convert.ToDateTime(Convert.ToInt32(ddlYear1.Text) + "/" + Convert.ToInt32(ddlMonth1.Text) + "/" + Convert.ToInt32(ddlDay1.Text));
                    if (_fromDate > dateTimeNow)
                    {
                        _isValid = false;
                        lblError.Text = Resources.General.ErrDatelessorequalToday;
                    }
                }
                else
                {
                    _isValid = false;
                    lblError.Text = Resources.General.ErrSelectValidDate;
                }
            }
            else
            {
                _isValid = false;
                lblError.Text = Resources.General.ErrSelectDate;
            }
        }
        else if (Convert.ToInt16(ddlReportType.Text) == 2)
        {
            if (ddlDay1.SelectedIndex >= 0 && ddlDay2.SelectedIndex >= 0)
            {
                if (ValidDate(Convert.ToInt32(ddlYear1.Text), Convert.ToInt32(ddlMonth1.Text), Convert.ToInt32(ddlDay1.Text)))
                {
                    _fromDate = Convert.ToDateTime(Convert.ToInt32(ddlYear1.Text) + "/" + Convert.ToInt32(ddlMonth1.Text) + "/" + Convert.ToInt32(ddlDay1.Text));
                    if (ValidDate(Convert.ToInt32(ddlYear2.Text), Convert.ToInt32(ddlMonth2.Text), Convert.ToInt32(ddlDay2.Text)))
                    {
                        _toDate = Convert.ToDateTime(Convert.ToInt32(ddlYear2.Text) + "/" + Convert.ToInt32(ddlMonth2.Text) + "/" + Convert.ToInt32(ddlDay2.Text));
                        if (_fromDate <= dateTimeNow)
                        {
                            if (_fromDate > _toDate)
                            {
                                _isValid = false;
                                lblError.Text = Resources.General.ErrFromdatelessthanTodate;
                            }
                        }
                        else
                        {
                            _isValid = false;
                            lblError.Text = Resources.General.ErrFromdatelessthanToday;
                        }
                    }
                    else
                    {
                        _isValid = false;
                        lblError.Text = Resources.General.ErrSelectValidTodate;
                    }
                }
                else
                {
                    _isValid = false;
                    lblError.Text = Resources.General.ErrSelectValidFromdate;
                }
            }
            else
            {
                _isValid = false;
                lblError.Text = Resources.General.ErrSelectFromandTodate;
            }
        }
        return _isValid;
    }

    public void LoadGrid()
    {
        lblError.Text = "";
        if (Validatioin() == true)
        {
            txtReportDate1.Text = "";
            txtReportDate2.Text = dateTimeNow.Year.ToString("0000") + dateTimeNow.Month.ToString("00") + dateTimeNow.Day.ToString("00");
            txtReportDate1.Text = ddlYear1.Text;
            txtReportDate1.Text += ddlMonth1.Text;
            txtReportDate1.Text += ddlDay1.Text;
            if (Convert.ToInt16(ddlReportType.Text) == 0)
            {
                txtReportDate1.Text = "";
                txtReportDate1.Text = ddlYear1.Text;
                txtReportDate1.Text += ddlMonth1.Text;
            }
            else if (Convert.ToInt16(ddlReportType.Text) == 1)
            {
                txtReportDate1.Text = "";
                txtReportDate1.Text = ddlYear1.Text;
                txtReportDate1.Text += ddlMonth1.Text;
                txtReportDate1.Text += ddlDay1.Text;
            }
            else if (Convert.ToInt16(ddlReportType.Text) == 2)
            {
                txtReportDate2.Text = ddlYear2.Text;
                txtReportDate2.Text += ddlMonth2.Text;
                txtReportDate2.Text += ddlDay2.Text;
            }
            DataTable _dtSummary = new DataTable();
            Int16 _ReportType = Convert.ToInt16(ddlReportType.Text);
            string _ReportDate1 = txtReportDate1.Text.Trim();
            string _ReportDate2 = txtReportDate2.Text.Trim();
            string _SearchKey = Server.HtmlEncode(txtSearch.Text);
            _SearchKey = _SearchKey.Replace("'", "");
            Int16 _AppStatus = Convert.ToInt16(ddlApplicationStatus.Text);
            Int16 _Language = Convert.ToInt16(lblLangOption.Text);

            MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
            string _spName = "[sprocCXCRMNonGGApplicationStatusSelectedList]";
            SortedList _sPara = new SortedList();

            _sPara.Add("@ReportType", _ReportType);
            _sPara.Add("@ReportDate1", _ReportDate1);
            _sPara.Add("@ReportDate2", _ReportDate2);
            _sPara.Add("@AppStatus", _AppStatus);
            _sPara.Add("@SearchKey", _SearchKey);

            _dtSummary = _db.GetDataTableBySP(_spName, _sPara);
            if (_dtSummary != null && _dtSummary.Rows.Count > 0)
            {
                lblError.Text = "";
                grvApplication.DataSource = _dtSummary;
                grvApplication.DataBind();
            }
            else
            {
                grvApplication.DataSource = null;
                grvApplication.DataBind();
                divUpdateStatus.Visible = false;
            }
        }
        else
        {
            grvApplication.DataSource = null;
            grvApplication.DataBind();
            divUpdateStatus.Visible = false;
        }
    }

    public void LoadPaymentStatusGrid()
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        string _spName = "sprocCXCRMPaymentsAmountsSelectItembyQuoteRefNo";
        SortedList _sPara = new SortedList();

        _sPara.Add("@QuoteRefNo", lblQuoteRefNo.Text);
        DataTable _dtPayment = _db.GetDataTableBySP(_spName, _sPara);
        if (_dtPayment != null && _dtPayment.Rows.Count > 0)
        {
            grvPaymentStatus.DataSource = _dtPayment;
            grvPaymentStatus.DataBind();
            divPaymentStatus.Visible = true;
        }
        else
        {
            grvPaymentStatus.DataSource = null;
            grvPaymentStatus.DataBind();
            divPaymentStatus.Visible = false;
        }

    }

    protected void btnGoToNonGGPendingApp_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/carinsurance/offline/NonGGPackageApplication.aspx?refno=" + lblQuoteRefNo.Text);
    }

    protected void ddlTransType_SelectedIndexChanged(object sender, EventArgs e)
    {
        divCustEmail.Visible = false;
        rfvCustEmail.Enabled = false;
        revCustEmail.Enabled = false;

        divTrackingNumber.Visible = false;
        rfvTrackingNumber.Enabled = false;
        divTrackingRemark.Visible = false;
        rfvTrackingRemark.Enabled = false; 

        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        string _spName = "[sprocCXCRMNonGGTransactionSelectItemByQuoteRefNo]";
        SortedList _sPara = new SortedList();

        _sPara.Add("@QuoteRefNo", lblQuoteRefNo.Text);
        if (ddlTransType.Text != "1000")
            _sPara.Add("@TransactionTypeId", ddlTransType.Text);

        DataTable _dtTrans = _db.GetDataTableBySP(_spName, _sPara);
        lblMessage.Text = string.Empty;
        lblMessage.ForeColor = System.Drawing.Color.Red;

        if (ddlTransType.Text == "200" && lblProviderCompanyID.Text == "43")
        {
            divProviderEmail.Visible = true;
        }
        else
        {
            divProviderEmail.Visible = false;
        }

        // *** Old ***
        //if (ddlTransType.Text == "300")
        //{
        //    lblRemark.Text = "Policy No.";
        //    txtRemark.TextMode = TextBoxMode.SingleLine;
        //    txtRemark.MaxLength = 50;
        //    txtRemark.Width = Unit.Pixel(200);
        //    divTransDate.Visible = true;
        //    divGrossPremium.Visible = true;
        //    rfvRemark.ErrorMessage = "Please enter Policy No.";
        //}
        //else if (ddlTransType.Text == "400")
        //{
        //    divCustEmail.Visible = true;
        //    rfvCustEmail.Enabled = true;
        //    revCustEmail.Enabled = true;
        //    GetCustomerEmail();
        //    lblRemark.Text = Resources.General.PORef;// "P.O Ref.";
        //    txtRemark.TextMode = TextBoxMode.SingleLine;
        //    txtRemark.MaxLength = 80;
        //    txtRemark.Width = Unit.Pixel(300);
        //    divTransDate.Visible = true;
        //    divGrossPremium.Visible = false;
        //    rfvRemark.ErrorMessage = "Please enter P.O Ref. No.";
        //}
        //else
        //{
        //    lblRemark.Text = Resources.NonGG.Remarks;// "Remarks";
        //    txtRemark.TextMode = TextBoxMode.MultiLine;
        //    txtRemark.MaxLength = 255;
        //    txtRemark.Width = Unit.Pixel(400);
        //    txtRemark.Columns = 50;
        //    txtRemark.Rows = 5;
        //    divTransDate.Visible = false;
        //    divGrossPremium.Visible = false;
        //    rfvRemark.ErrorMessage = "Please enter some remarks.";
        //}

        // *** New ***
        if (ddlTransType.Text == "1000")
        {
            lblRemark.Text = "Policy No.";
            txtRemark.TextMode = TextBoxMode.SingleLine;
            txtRemark.MaxLength = 50;
            txtRemark.Width = Unit.Pixel(200);
            rfvRemark.ErrorMessage = "Please enter Policy No.";

            divTransDate.Visible = false;
            divCustEmail.Visible = true;
            rfvCustEmail.Enabled = true;
            revCustEmail.Enabled = true;
            divTrackingNumber.Visible = true;
            rfvTrackingNumber.Enabled = true;

            divTrackingRemark.Visible = true;
            rfvTrackingRemark.Enabled = true;

            GetCustomerEmail();
            divGrossPremium.Visible = true;
        }
        else
        {
            lblRemark.Text = Resources.NonGG.Remarks;// "Remarks";
            txtRemark.TextMode = TextBoxMode.MultiLine;
            txtRemark.MaxLength = 255;
            txtRemark.Width = Unit.Pixel(400);
            txtRemark.Columns = 50;
            txtRemark.Rows = 5;
            divTransDate.Visible = false;
            divGrossPremium.Visible = false;
            rfvRemark.ErrorMessage = "Please enter some remarks.";
        }
        // ***********

        if (divTransDate.Visible)
        {
            ddlTransDay.Text = dateTimeNow.ToString("dd");
            ddlTransMonth.Text = dateTimeNow.ToString("MMM");
            ddlTransYear.Text = dateTimeNow.ToString("yyyy");
        }

        if (ddlTransType.Text == "-1" || ddlTransType.Text == "0")
        {
            btnUpdateStatus.Enabled = false;
        }
        else
        {
            btnUpdateStatus.Enabled = true;
        }

        if (Session[General.UserRole].ToString() == "200")
        {
            if (ddlTransType.Text == "101" || ddlTransType.Text == "100")
            {
                btnUpdateStatus.Enabled = false;
            }
        }

        if (ddlTransType.Text == "100")
        {
            float _balanceAmount = 0.0f;
            if (float.TryParse(txtBalanceAmount.Text, out _balanceAmount))
            {
                if (_balanceAmount > 0)
                {
                    lblMessage.Text = "Please check balance amount.";
                    lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                    btnUpdateStatus.Enabled = false;
                }
                else if (_balanceAmount == 0)
                {
                    if (lblPaymentApprovalStatus.Text == "1")
                    {
                        btnUpdateStatus.Enabled = true;
                        lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Black;
                    }
                    else
                    {
                        lblMessage.Text = "One or more payment transaction(s) are NOT approved yet.";
                        lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                        //return;
                    }
                }
                else
                {
                    lblMessage.Text = "Invalid balance amount.";
                    lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                    btnUpdateStatus.Enabled = false;
                }
            }
            else
            {
                lblMessage.Text = "Invalid balance amount.";
                lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                btnUpdateStatus.Enabled = false;
                //return;
            }
        }

        // *** Old ***
        //if (ddlTransType.Text == "400")
        // *** New ***
        if (ddlTransType.Text == "1000")
        {
            if (lblDocumentUploadStatus.Text == "0")
            {
                lblMessage.Text = "Please check uploaded documents listing.";
            }
        }

        if (_dtTrans != null && _dtTrans.Rows.Count > 0)
        {
            if (ddlTransType.Text != "1000")
            {
                lblTransID.Text = _dtTrans.Rows[0]["TransactionID"].ToString();

                txtRemark.Text = _dtTrans.Rows[0]["Remarks"].ToString();
                lblMessage.Text = "Last updated at " + Convert.ToDateTime(_dtTrans.Rows[0]["ModifiedDate"].ToString()).ToString("dd/MMM/yyyy hh:mm tt");

                txtGrossPremium.Text = "0";
            }
            else
            {
                //300
                DataRow[] _drTrans300 = _dtTrans.Select("TransactionTypeID = 300");
                if (_drTrans300 != null && _drTrans300.Length > 0)
                {
                    lblTransID.Text = _drTrans300[0]["TransactionID"].ToString();
                    txtRemark.Text = _drTrans300[0]["Remarks"].ToString();

                    float _grossPremium = 0.0f;
                    if (float.TryParse(_drTrans300[0]["FInfo1"].ToString(), out _grossPremium))
                    {
                        txtGrossPremium.Text = _grossPremium.ToString("#.00");
                    }
                }
                else
                {
                    if (grvPaymentStatus.Rows.Count > 0)
                    {
                        txtGrossPremium.Text = grvPaymentStatus.Rows[0].Cells[3].Text;
                    }
                }
                //400
                DataRow[] _drTrans400 = _dtTrans.Select("TransactionTypeID = 400");
                if (_drTrans400 != null && _drTrans400.Length > 0)
                {
                    lblTransID2.Text = _drTrans400[0]["TransactionID"].ToString();
                    txtTrackingNumber.Text = _drTrans400[0]["Remarks"].ToString();
                }
                //1000
                DataRow[] _drTrans1000 = _dtTrans.Select("TransactionTypeID = 1000");
                if (_drTrans1000 != null && _drTrans1000.Length > 0)
                {
                    btnCoverPage.Visible = true;
                    lblTransID3.Text = _drTrans1000[0]["TransactionID"].ToString();
                    txtTrackingRemark.Text = _drTrans1000[0]["Remarks"].ToString();
                    lblMessage.Text = "Last updated at " + Convert.ToDateTime(_drTrans1000[0]["ModifiedDate"].ToString()).ToString("dd/MMM/yyyy hh:mm tt");
                }
            }
            
            // *** Old *** (???)
            //if (Convert.ToInt32(ddlTransType.Text) == 400)
            //{
            //    btnUpdateStatus.Enabled = true;
            //}
            //else
            //{
            //    btnUpdateStatus.Enabled = false;
            //}
            
            btnUpdateStatus.Enabled = true;
        }
        else
        {
            lblTransID.Text = "-1";
            
            txtRemark.Text = string.Empty;
            if (lblMessage.Text != string.Empty)
            {
                lblMessage.Text += "<br/>[No transaction found.]";
            }
            else
            {
                lblMessage.Text = "No transaction found.";
            }
            btnUpdateStatus.Enabled = true;
        }

        if (Session[General.UserRole].ToString() == "100")
        {
            btnUpdateStatus.Enabled = false;
        }
    }

    protected void btnUpdateStatus_Click(object sender, EventArgs e)
    {
        try
        {
            lblMessage.Text = string.Empty;
            lblMessage.ForeColor = System.Drawing.Color.Red;
            if (Session[General.UserRole].ToString() == "100")
            {
                btnUpdateStatus.Enabled = false;
                lblMessage.Text = "Invalid transaction. You are NOT allowed.";
                return;
            }

            if (ddlTransType.Text == "200")
            {
                if (hplExcelDownLoad.NavigateUrl != string.Empty)
                {
                    if (SendToProvider())
                    {
                        lblMessage.Text = "Sending mail to provider was SUCCEEDED!";
                    }
                    else
                    {
                        lblMessage.Text = "Sending mail to provider was FAILED!";
                        return;
                    }
                }
                else
                {
                    lblMessage.Text = "FOUND application changes.<br/>Please verify and update App Details again.";
                    return;
                }
            }

            if (ddlTransType.Text == "100")
            {
                float _balanceAmount = 0.0f;
                if (float.TryParse(txtBalanceAmount.Text, out _balanceAmount))
                {
                    if (_balanceAmount > 0)
                    {
                        lblMessage.Text = "Please check balance amount.";
                        lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                        return;
                    }
                    else if (_balanceAmount == 0)
                    {
                        if (lblPaymentApprovalStatus.Text == "1")
                        {
                            lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Black;
                        }
                        else
                        {
                            lblMessage.Text = "One or more payment transaction(s) are NOT approved yet.";
                            lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                            return;
                        }
                    }
                    else
                    {
                        lblMessage.Text = "Invalid balance amount.";
                        lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                        return;
                    }
                }
                else
                {
                    lblMessage.Text = "Invalid balance amount.";
                    lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                    return;
                }
            }
            else if (ddlTransType.Text == "101")
            {
                if (Session[General.UserRole].ToString() != "300")
                {
                    btnUpdateStatus.Enabled = false;
                    lblMessage.Text = "Invalid transaction. You are NOT allowed.";
                    return;
                }
            }

            DateTime _dtTransDate = dateTimeNow;

            // *** Old ***
            // if (ddlTransType.Text == "400")
            // *** New ***
            if (ddlTransType.Text == "1000")
            {
                if (lblDocumentUploadStatus.Text == "0")
                {
                    lblMessage.Text = "Please check uploaded documents listing.";
                    return;
                }
            }
            else
            {
                if (divTransDate.Visible)
                {
                    string _strTransDate = ddlTransDay.Text + "/" + ddlTransMonth.Text + "/" + ddlTransYear.Text;
                    if (!DateTime.TryParse(_strTransDate, out _dtTransDate))
                    {
                        lblMessage.Text = "Invalid selected date.";
                        return;
                    }
                }
            }
            
            MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
            string _spName = "[sprocCXCRMNonGGTransactionInsertUpdateSingleItem]";
            SortedList _sPara = new SortedList();

            if (Session[General.UserRole].ToString() == "100")
            {
                _sPara.Add("@AgentID", Session[General.UserId].ToString());
                _sPara.Add("@AdminID", 0);
            }
            else
            {
                _sPara.Add("@AdminID", Session[General.UserId].ToString());
                _sPara.Add("@AgentID", 0);
            }
            _sPara.Add("@CECarID", lblCarID.Text);
            _sPara.Add("@RefCEUserID", lblCustomerID.Text);
            _sPara.Add("@ProviderCompanyID", lblProviderCompanyID.Text);
            _sPara.Add("@QuoteRefNo", lblQuoteRefNo.Text);
            _sPara.Add("@Status", chkStatus.Checked);

            // *** Old ***
            //if (ddlTransType.Text == "300" || ddlTransType.Text == "400")
            //{
            //    _sPara.Add("@Info1", _dtTransDate.ToString("dd/MMM/yyyy"));
            //}
            //if (ddlTransType.Text == "400")
            //{
            //    _sPara.Add("@Info2", txtCustEmail.Text);
            //}
            //if (ddlTransType.Text == "300")
            //{
            //    _sPara.Add("@FInfo1", txtGrossPremium.Text);
            //}
            // *** New ***
            Boolean IsNewTracking = false;
            Int64 _transID = 0;
            if (ddlTransType.Text != "1000")
            {
                _sPara.Add("@TransactionID", lblTransID.Text);
                _sPara.Add("@TransactionTypeId", ddlTransType.Text);
                _sPara.Add("@Remarks", txtRemark.Text);
                _transID = Convert.ToInt64(_db.ExecuteNonSqlSP(_spName, _sPara));
                if (_transID > 0) lblTransID.Text = _transID.ToString();
            }
            else
            {
                _sPara.Add("@TransactionID", lblTransID.Text);
                _sPara.Add("@TransactionTypeId", "300");
                _sPara.Add("@Remarks", txtRemark.Text);
                _sPara.Add("@Info1", _dtTransDate.ToString("dd/MMM/yyyy"));
                _sPara.Add("@FInfo1", txtGrossPremium.Text);
                _transID = Convert.ToInt64(_db.ExecuteNonSqlSP(_spName, _sPara));
                if (_transID > 0)
                {
                    if (lblTransID2.Text.Trim() == "" || lblTransID2.Text.Trim() == "-1" || 
                        lblTransID2.Text.Trim() == "0") IsNewTracking = true;
                    lblTransID.Text = _transID.ToString();
                    _transID = 0;
                    _sPara.Remove("@TransactionID");
                    _sPara.Remove("@TransactionTypeId");
                    _sPara.Remove("@Remarks");
                    _sPara.Remove("@Info1");
                    _sPara.Remove("@FInfo1");
                    _sPara.Add("@TransactionID", lblTransID2.Text);
                    _sPara.Add("@TransactionTypeId", "400");
                    _sPara.Add("@Remarks", txtTrackingNumber.Text);
                    _sPara.Add("@Info2", txtCustEmail.Text);
                    _sPara.Add("@Info1", _dtTransDate.ToString("dd/MMM/yyyy"));
                    _transID = Convert.ToInt64(_db.ExecuteNonSqlSP(_spName, _sPara));
                    if (_transID > 0)
                    {
                        lblTransID2.Text = _transID.ToString();
                        _transID = 0;
                        _sPara.Remove("@TransactionID");
                        _sPara.Remove("@TransactionTypeId");
                        _sPara.Remove("@Remarks");
                        _sPara.Remove("@Info1");
                        _sPara.Remove("@Info2");
                        _sPara.Add("@TransactionID", lblTransID3.Text);
                        _sPara.Add("@TransactionTypeId", "1000");
                        _sPara.Add("@Remarks", txtTrackingRemark.Text);
                        _transID = Convert.ToInt64(_db.ExecuteNonSqlSP(_spName, _sPara));
                        if (_transID > 0) lblTransID3.Text = _transID.ToString();
                    }
                }
            }

            if (_transID > 0)
            {
                lblMessage.ForeColor = System.Drawing.Color.Green;
                if (ddlTransType.Text == "100")
                {
                    lblPaymentStatus.Text = "1";
                }
                else if (ddlTransType.Text == "101")
                {
                    lblPaymentStatus.Text = "101";
                }
                else if (ddlTransType.Text == "200")
                {
                    txtRemark.Text = "";
                    lblSendToProviderStatus.Text = "1";
                }
                // *** Old ***
                //else if (ddlTransType.Text == "300")
                //{
                //    lblPolicyIssuedStatus.Text = "1";
                //}
                //else if (ddlTransType.Text == "400")
                //{
                //    lblMailingStatus.Text = "1";
                //}
                else if (ddlTransType.Text == "1000")
                {
                    lblPolicyIssuedStatus.Text = "1";
                    lblMailingStatus.Text = "1";
                    lblCompletedStatus.Text = "1";
                    btnCoverPage.Visible = true;

                    if (IsNewTracking)
                        SendMailingStatusToCustomer();
                }
                // *** Old ***
                //if (ddlTransType.Text == "400")
                //{
                //    SendMailingStatusToCustomer();
                //}
                if (lblMessage.Text != string.Empty)
                {

                    lblMessage.Text += "&nbsp;Succeeded at " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
                }
                else
                {
                    lblMessage.Text = "Succeeded at " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
                }

                CheckApplicationStatus();
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + ddlTransType.SelectedItem.Text + " transaction was SAVED');", true);

                lblTransID.Text = "-1";
                lblTransID2.Text = "-1";
                lblTransID3.Text = "-1";
                UpdateStatusList();
            }
            else
            {
                if (lblMessage.Text != string.Empty)
                {
                    lblMessage.Text += "&nbsp;Failed at " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
                }
                else
                {
                    lblMessage.Text = "Failed at " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
                }

                ClientScript.RegisterStartupScript(this.GetType(), "JS_MessageAlert", "alert('" + ddlTransType.SelectedItem.Text + " was FAILED');", true);
            }
        }
        catch (Exception Ex)
        {
            lblMessage.Text = Ex.Message;
        }
    }

    private bool SendToProvider()
    {
        bool _retValue = false;

        string _QuoteRefNo = lblQuoteRefNo.Text;
        string[] _fileList = new string[0];
        string[] _fileType = new string[0];
        DataSet _dsCarFileUpload = new DataSet(); 
        string Language = "EN";
        if (lblLangOption.Text == "1")
            Language = "TH"; 
        Int16 Renewal = 0;
        if (lblAppType.Text == "REN" || lblAppType.Text == "RNO")
        {
            Renewal = 1;
        }
        CarFileUploadDB _carfileuploaddb = new CarFileUploadDB();
        _dsCarFileUpload = _carfileuploaddb.GetNonGGCarFileUploadList(Convert.ToInt64(lblCarID.Text.Trim()), Convert.ToInt64(lblProviderCompanyID.Text.Trim()), Language, Renewal);
        if (_dsCarFileUpload != null && _dsCarFileUpload.Tables.Count > 3)
        {
            if (_dsCarFileUpload.Tables[3].Rows.Count > 0)
            {
                _fileList = new string[_dsCarFileUpload.Tables[3].Rows.Count + 1];
                _fileType = new string[_dsCarFileUpload.Tables[3].Rows.Count + 1];
                for (int b = 0; b < _dsCarFileUpload.Tables[3].Rows.Count; b++)
                {
                    _fileList[b] = _dsCarFileUpload.Tables[3].Rows[b]["FilePath"].ToString();
                    _fileType[b] = _dsCarFileUpload.Tables[3].Rows[b]["FileType"].ToString().Replace(' ', '_');
                }
            }

            if (_fileList.Length == 0)
            {
                _fileList = new string[_dsCarFileUpload.Tables[2].Rows.Count];
                _fileType = new string[_dsCarFileUpload.Tables[2].Rows.Count];
            }

            if (_dsCarFileUpload.Tables.Count > 2 && _dsCarFileUpload.Tables[2].Rows.Count > 0)
            {
                _fileList[_fileList.Length - 1] = _dsCarFileUpload.Tables[2].Rows[0]["FileName"].ToString();
                _fileType[_fileType.Length - 1] = "Application";
            }
        }

        string _ProMailBody, _ProEmailTitle, _ProToEmail, _ProCCEmail, _ProBCCEmail, _ProviderName, ProviderBrokerCode;
        _ProMailBody = ""; _ProEmailTitle = ""; _ProToEmail = ""; _ProCCEmail = ""; _ProBCCEmail = "";
        _ProviderName = CE.Global.General.GetProviderName(Convert.ToInt64(lblProviderCompanyID.Text.Trim()));
        ProviderBrokerCode = CE.Global.General.GetProviderBrokerCode(Convert.ToInt64(lblProviderCompanyID.Text.Trim()));
        
        string imgUrl = "http://" + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
        
        _ProEmailTitle = "[" + lblQuoteRefNo.Text + "] ส่งงานประกันรถ คุณ [" + lblCustomerName.Text + "] [" + lblCarPlate.Text + "]";
        _ProMailBody += "<br>เรียน ฝ่ายพิจารณารับประกัน บริษัท  " + _ProviderName + ",<br/><br/>";
        _ProMailBody += "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด, เลขที่นายหน้า [" + ProviderBrokerCode + "]  มีความประสงค์ขอส่งงานประกันภัยรถยนต์ตามรายละเอียดในไฟล์แนบ<br><br>";
        _ProMailBody += "กรุณาติดต่อ 0-2268-8222 หากข้อมูลไม่ครบถ้วน หรือหากต้องการสอบถามรายละเอียดเพิ่มเติม ขอบคุณค่ะ<br/><br/>";

        if (txtRemark.Text != string.Empty)
        {
            _ProMailBody += "<div style='padding: 5px; border: 2px solid red;'>";
            _ProMailBody += "<strong style='color:red;'>" + Resources.General.Comments + ": </strong>";
            _ProMailBody += txtRemark.Text + "</div><br/><br/>";
        }
        _ProMailBody += "ขอแสดงความนับถือ<br/><br/>";
        _ProMailBody += "<a href='http://www.gluaygluay.com'>กล้วยๆ.com</a> - เราทำให้ประกันรถยนต์เป็นเรื่อง กล้วยๆ<br/><br/>";
        _ProMailBody += "<img src=" + imgUrl + "  alt='GluayGluay' width='120' height='100' /><br/>";
        
        _ProMailBody += "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด<br/>" +
                    "เลขทะเบียนนายหน้าประกันวินาศภัยนิติบุคคล เลขที่ ว00016/2553<br/>" +
                    "ชั้น 42 อาคารยูไนเต็ด เซ็นเตอร์ เลขที่ 323 ถนนสีลม แขวงสีลม เขตบางรัก กรุงเทพฯ 10500<br/>" +
                    "โทร. 02-268-8222 โทรสาร 02-266-6339<br/>" +
                    "อีเมล์: support@gluaygluay.com<br/>" +
                    "กด Like เพื่อติดตามเราได้ใน Facebook: www.facebook.com/GGmotor";

        string _ProkiderKey = CE.Global.General.GetProviderMail(Convert.ToInt64(lblProviderCompanyID.Text.Trim()));
       

        if (lblProviderCompanyID.Text == "43")
        {
            _ProToEmail = txtProviderEmail.Text;
        }
        else
        {
            _ProToEmail = CE.Configuration.MyConfigurationManager.GetAppSettingValue(_ProkiderKey);
        }

        

        _ProCCEmail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
        _ProCCEmail += CE.Configuration.MyConfigurationManager.GetAppSettingValue("CASH");

        _ProBCCEmail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("BCC");

        _retValue = MyMailManager.SendProviderGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _ProToEmail, _ProCCEmail, _ProBCCEmail, _ProEmailTitle, _ProMailBody, Session[General.SMTPReplyTo].ToString(), _fileList, _fileType, _QuoteRefNo);

       

        return _retValue;
    }

    public void LoadUploadDocument()
    {
        if (lblCarID.Text != string.Empty && lblProviderCompanyID.Text != string.Empty)
        {
            MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
            string _spName = "sprocCXCRMNonGGCarFileUploadDetailSelectItemList";
            string Language = "EN";
            if (lblLangOption.Text == "1")
                Language = "TH";
            Int16 Renewal = 0;
            if (lblAppType.Text == "REN" || lblAppType.Text == "RNO")
            {
                Renewal = 1;
            }
            SortedList _spara = new SortedList();
            _spara.Add("@CECarId", Convert.ToInt64(lblCarID.Text));
            _spara.Add("@ProviderCompanyId", Convert.ToInt64(lblProviderCompanyID.Text));
            _spara.Add("@Language", Language);
            _spara.Add("@Renewal", Renewal);
            DataSet _dsUploadDocument = new DataSet();
            _dsUploadDocument = _db.GetDataSet(_spName, _spara);
            divUploadDocs.Visible = true;
            grvFileUpload.Visible = true;
            if (_dsUploadDocument != null && _dsUploadDocument.Tables.Count > 3 && _dsUploadDocument.Tables[3].Rows.Count > 0)
            {
                grvFileUpload.DataSource = _dsUploadDocument.Tables[3];
                grvFileUpload.DataBind();

                if (grvFileUpload.Rows.Count > 0)
                {
                   
                    lblDocumentUploadStatus.Text = "1";
                    lblUploadDocTitle.ForeColor = System.Drawing.Color.Green;
                }
                else
                {
                   
                    lblUploadDocTitle.ForeColor = System.Drawing.Color.Red;
                    lblDocumentUploadStatus.Text = "0";
                }
            }
            else
            {
                grvFileUpload.DataSource = null;
                grvFileUpload.DataBind();
                lblUploadDocTitle.ForeColor = System.Drawing.Color.Red;
                lblDocumentUploadStatus.Text = "0";
              
            }
        }
        else
        {
            grvFileUpload.DataSource = null;
            grvFileUpload.DataBind();
            divUploadDocs.Visible = false;
            lblDocumentUploadStatus.Text = "0";
        }
    }

    protected void grvFileUpload_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink hplk = (HyperLink)e.Row.FindControl("hplDownLoad");
            Label Path = (Label)e.Row.FindControl("lblPath");

            if (hplk != null)
            {
                hplk.NavigateUrl = "DownLoad/UploadNonGGHandler.ashx?FileName=" + Path.Text;
            }

            Label FileName = (Label)e.Row.FindControl("lblPDFFileName");
            Label FileType = (Label)e.Row.FindControl("lblPDFFileType");
            string strFileName = FileName.Text;
            System.IO.FileInfo _File = new System.IO.FileInfo(strFileName.ToString());
            FileName.Text = FileType.Text.Replace(' ', '_') + "_" + lblQuoteRefNo.Text + "_" + (e.Row.RowIndex + 1).ToString() + _File.Extension;

        }
    }

    private void LoadNonAppDetail()
    {
        lblCustomerAddress1.Text = string.Empty;
        lblCustomerAddress2.Text = string.Empty;
        lblCustomerAddress3.Text = string.Empty;
        lblCarMakeModel.Text = string.Empty;
        lblTypeOfPolicy.Text = string.Empty;

        if (lblCarID.Text != string.Empty && lblCustomerID.Text != string.Empty && lblProviderCompanyID.Text != string.Empty)
        {
            NonGGPackageDB _app = new NonGGPackageDB();
            DataSet _ds = _app.GetNonGGApplication(Convert.ToInt64(lblCarID.Text), Convert.ToInt64(lblProviderCompanyID.Text), 0);
            if (_ds != null && _ds.Tables.Count > 0 && _ds.Tables[0].Rows.Count > 0)
            {
                txtConfirmEmail.Text = _ds.Tables[0].Rows[0]["Email"].ToString();
                lblCustomerAddress1.Text = _ds.Tables[0].Rows[0]["PresentAddress"].ToString();
                lblCustomerAddress2.Text = _ds.Tables[0].Rows[0]["SubDistrict"].ToString();
                lblCustomerAddress2.Text += ", " + _ds.Tables[0].Rows[0]["District"].ToString();

                lblCustomerAddress3.Text = _ds.Tables[0].Rows[0]["Province"].ToString();
                lblCustomerAddress3.Text += ", Thailand";
                lblCustomerAddress3.Text += " " + _ds.Tables[0].Rows[0]["Postalcode"].ToString();

                lblCarMakeModel.Text = _ds.Tables[0].Rows[0]["CarMakeModel"].ToString();
                lblTypeOfPolicy.Text = _ds.Tables[0].Rows[0]["InsuranceType"].ToString();

                if (lblProviderCompanyID.Text == "43")
                {
                    
                    if (_ds.Tables[0].Rows[0]["Info3"] != DBNull.Value && _ds.Tables[0].Rows[0]["Info3"].ToString().Length > 0)
                    {
                        txtProviderEmail.Text = _ds.Tables[0].Rows[0]["Info3"].ToString();
                    }
                }
            }
        }

    }

    protected void btnExcelDownload_Click(object sender, EventArgs e)
    {
        Response.Redirect(hplExcelDownLoad.NavigateUrl);
    }

    protected void btnCoverPage_Click(object sender, EventArgs e)
    {
        CoverPagePDFOutput _coverpage = new CoverPagePDFOutput();

        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        string _spName = "[sprocCXCRMNonGGTransactionSelectItemByQuoteRefNo]";
        SortedList _sPara = new SortedList();
        _sPara.Add("@QuoteRefNo", lblQuoteRefNo.Text);
        _sPara.Add("@TransactionTypeId", "300");
        DataTable _dtTrans = _db.GetDataTableBySP(_spName, _sPara);

        if (_dtTrans.Rows.Count > 0)
        {
            _coverpage.PolicyNo = _dtTrans.Rows[0]["Remarks"].ToString();

            NonGGPackageDB _app = new NonGGPackageDB();
            DataSet _ds = _app.GetNonGGApplication(Convert.ToInt64(lblCarID.Text), Convert.ToInt64(lblProviderCompanyID.Text), 0);
            if (_ds != null && _ds.Tables.Count > 0 && _ds.Tables[0].Rows.Count > 0)
            {
                _coverpage.RefNumber = lblQuoteRefNo.Text;
                _coverpage.CustomerName = _ds.Tables[0].Rows[0]["Name"].ToString();
                _coverpage.LicensePlate = _ds.Tables[0].Rows[0]["CarPlate"].ToString();
                if (_ds.Tables[0].Rows[0]["IsMailingAddressDiff"] != null &&
                    _ds.Tables[0].Rows[0]["IsMailingAddressDiff"].ToString() == "True")
                {
                    _coverpage.MailName = _ds.Tables[0].Rows[0]["MailingName"].ToString();
                    _coverpage.MailAddress = _ds.Tables[0].Rows[0]["MailingAddress"].ToString();
                    _coverpage.MailSubDistrict = _ds.Tables[0].Rows[0]["MailingSubDistrict"].ToString();
                    _coverpage.MailDistrict = _ds.Tables[0].Rows[0]["MailingDistrict"].ToString();
                    _coverpage.MailProvince = _ds.Tables[0].Rows[0]["MailingProvince"].ToString();
                    _coverpage.MailPostCode = _ds.Tables[0].Rows[0]["MailingPostalCode"].ToString();
                }
                else
                {
                    _coverpage.MailName = "";
                    _coverpage.MailAddress = _ds.Tables[0].Rows[0]["PresentAddress"].ToString();
                    _coverpage.MailSubDistrict = _ds.Tables[0].Rows[0]["SubDistrict"].ToString();
                    _coverpage.MailDistrict = _ds.Tables[0].Rows[0]["District"].ToString();
                    _coverpage.MailProvince = _ds.Tables[0].Rows[0]["Province"].ToString();
                    _coverpage.MailPostCode = _ds.Tables[0].Rows[0]["Postalcode"].ToString();
                }

                string refNumber = _ds.Tables[0].Rows[0]["QuoteRefNo"].ToString();
                _coverpage.InsuranceCode = refNumber.Substring(0, 3);

                string filePath = _coverpage.GeneratePDF();
                if (filePath != "")
                {
                    filePath = "DownLoad/CoverPageHandler.ashx?FileName=" + filePath;
                    filePath = filePath.Replace(@"\", "|");
                    ScriptManager.RegisterStartupScript(Page, typeof(Page), "CoverPage", "window.open('" + filePath + "');", true);
                }
            }
        }
    }

    public void GetCarDocumentDetails()
    {
        hplExcelDownLoad.NavigateUrl = string.Empty;
        hplExcelDownLoad.Visible = false;

        if (lblCarID.Text != string.Empty && lblCustomerID.Text != string.Empty && lblProviderCompanyID.Text != string.Empty)
        {
            MyIO _myIO = new MyIO();
            MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
            string _spName = "sprocCXCRMNonGGCarFileUploadDetailSelectItemList";
            SortedList _spara = new SortedList();
            _spara.Add("@CECarId", Convert.ToInt64(lblCarID.Text));
            _spara.Add("@ProviderCompanyId", Convert.ToInt64(lblProviderCompanyID.Text));
            DataSet _dsCarDocumentDetails = new DataSet();
            _dsCarDocumentDetails = _db.GetDataSet(_spName, _spara);

            if (_dsCarDocumentDetails != null && _dsCarDocumentDetails.Tables.Count > 2)
            {
                if (_dsCarDocumentDetails.Tables[2].Rows.Count > 0)
                {
                    if (_dsCarDocumentDetails.Tables[2].Rows[0]["FileName"] != null
                        && _dsCarDocumentDetails.Tables[2].Rows[0]["FileName"].ToString() != string.Empty)
                    {
                        hplExcelDownLoad.NavigateUrl = "download/nongghandler.ashx?fileName=test.xls&carId=" + lblCarID.Text.Trim() + "&userId=" + lblCustomerID.Text.Trim() + "&providerId=" + lblProviderCompanyID.Text.Trim();
                        hplExcelDownLoad.Visible = true;
                    }
                }
                else
                {
                    hplExcelDownLoad.Visible = false;
                }
            }
            else
            {
                hplExcelDownLoad.Visible = false;
            }

        }

    }

    public void LoadPaymentDetailList()
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocCXCRMBrokerPremiumSelectSingleItem";
        _sPara.Add("@CXBrokerProviderId", Convert.ToInt64(lblProviderCompanyID.Text));
        _sPara.Add("@CECarId", Convert.ToInt64(lblCarID.Text.Trim()));
        _sPara.Add("@SelectedStatus", true);
        DataSet _dsPayment = new DataSet();
        _dsPayment = _db.GetDataSet(_spName, _sPara);

        txtBalanceAmount.Text = "0";
        txtTotalCollectedAmount.Text = "0";
        txtTotalRefundAmount.Text = "0";
        lblPaymentCash.Text = "0";
        lblPaymentCreditCard.Text = "0";
        lblPaymentBankTransfer.Text = "0";
        lblPaymentVisa.Text = "0";
        lblPaymentMaster.Text = "0";
        lblPaymentCheckNo.Text = "0";
        lblInstallment.Text = "0";
        if (_dsPayment != null && _dsPayment.Tables.Count > 1 && _dsPayment.Tables[1].Rows.Count > 0)
        {
            grvPayment.DataSource = _dsPayment.Tables[1];
            grvPayment.DataBind();
            lblPaymentApprovalStatus.Text = "1";

            for (int i = 0; i < _dsPayment.Tables[1].Rows.Count; i++)
            {
                if (_dsPayment.Tables[1].Rows[i]["ApproveType"].ToString() == "0" && _dsPayment.Tables[1].Rows[i]["Status"].ToString() == "1")
                {
                    lblPaymentApprovalStatus.Text = "0";

                    //break;
                }

                string _paymentType = _dsPayment.Tables[1].Rows[i]["PaymentTypeID"].ToString().ToLower();
                string _cardType = _dsPayment.Tables[1].Rows[i]["CardType"].ToString().ToLower();
                string _payoption = _dsPayment.Tables[1].Rows[i]["PaymentOptionId"].ToString().ToLower();
                if (_paymentType == "cash")
                {
                    lblPaymentCash.Text = "1";
                }
                else if (_paymentType == "bktr")
                {
                    lblPaymentBankTransfer.Text = "1";
                }
                else if (_paymentType == "ccip" || _paymentType == "ccol")
                {
                    lblPaymentCreditCard.Text = "1";
                    if (_cardType == "visa")
                    {
                        lblPaymentVisa.Text = "1";
                    }
                    else if (_cardType == "mastercard")
                    {
                        lblPaymentMaster.Text = "1";
                    }
                    lblInstallment.Text = "0";
                    if (_payoption == "ip")
                    {
                        lblInstallment.Text = "1";
                    }
                }
            }

            if (grvPayment.Rows.Count > 0)
            {
                DataSet _dsPaymentAmount = new DataSet();
                _dsPaymentAmount = GetPaymentAmounts();
                if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
                {
                    txtFinalAnnualPremium.Text = _dsPaymentAmount.Tables[0].Rows[0]["PremiumAmount"].ToString();
                    txtBalanceAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["BalanceAmount"].ToString();
                    txtTotalCollectedAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString();
                    txtTotalRefundAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["RefundAmount"].ToString();
                }
            }
        }
        else
        {
            grvPayment.DataSource = null;
            grvPayment.DataBind();
            lblPaymentApprovalStatus.Text = "0";
        }
    }

    public DataSet GetPaymentAmounts()
    {
        DataSet _ds = new DataSet();
        if (lblQuoteRefNo.Text != string.Empty)
        {
            MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
            SortedList _sPara = new SortedList();
            string _spName = "sprocCXCRMPaymentsAmountsSelectItembyQuoteRefNo";
            _sPara.Add("@QuoteRefNo", lblQuoteRefNo.Text);
            _ds = _db.GetDataSet(_spName, _sPara);
        }
        return _ds;
    }

    protected void btnPaymentReceiptDownload_Click(object sender, EventArgs e)
    {
        lblPaymentReceiptMessage.Text = string.Empty;

        if (Session[General.UserRole].ToString() == "100")
        {
            btnSendPaymentReceipt.Enabled = false;
            btnPaymentReceiptDownload.Enabled = false;
            return;
        }

        if (grvPayment.Rows.Count > 0)
        {
            float _balanceAmount = 0.0f;
            if (float.TryParse(txtBalanceAmount.Text, out _balanceAmount))
            {
                if (_balanceAmount > 0)
                {
                    lblPaymentReceiptMessage.Text = "Please check balance amount.";
                    return;
                }
                else if (_balanceAmount == 0)
                {
                    if (lblPaymentApprovalStatus.Text == "0")
                    {
                        lblPaymentReceiptMessage.Text = "One or more payment transaction(s) are NOT approved yet.";
                        lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                        return;
                    }
                }
                else
                {
                    lblPaymentReceiptMessage.Text = "Invalid balance amount.";
                    lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                    btnUpdateStatus.Enabled = false;
                }
            }
            else
            {
                lblPaymentReceiptMessage.Text = "Invalid balance amount.";
                lblPaymentDetailsTitle.ForeColor = System.Drawing.Color.Red;
                btnUpdateStatus.Enabled = false;
                return;
            }

            PaymentReceiptPDFOutput _paymentPdf = CreatePaymentPDFObject();

            string _fileName = _paymentPdf.GeneratePDF();
            FileInfo file = new System.IO.FileInfo(_fileName);
            if (!file.Exists)
            {
                Response.StatusCode = 500;
                Response.End();
                return;
            }
            Response.Clear();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();
            Response.Cache.SetExpires(DateTime.MinValue);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.WriteFile(file.FullName);
            ApplicationInstance.CompleteRequest();
            Response.End();
        }
        else
        {
            ClientScript.RegisterStartupScript(btnPaymentReceiptDownload.GetType(), "DownloadPremiumAlert", "alert('No item to download!');", true);
        }
    }

    private PaymentReceiptPDFOutput CreatePaymentPDFObject()
    {
        PaymentReceiptPDFOutput _paymentPDF = new PaymentReceiptPDFOutput();
        _paymentPDF.QuoteRefNo = lblQuoteRefNo.Text;
        _paymentPDF.CustomerName = lblCustomerName.Text;
        _paymentPDF.Address1 = lblCustomerAddress1.Text;
        _paymentPDF.Address2 = lblCustomerAddress2.Text;
        _paymentPDF.Address3 = lblCustomerAddress3.Text;
        _paymentPDF.AnnualPremium = txtFinalAnnualPremium.Text;
        _paymentPDF.TypeOfPolicy = lblTypeOfPolicy.Text;
        _paymentPDF.MakeModel = lblCarMakeModel.Text;

        if (lblPaymentBankTransfer.Text == "1")
        {
            _paymentPDF.IsBankTransfer = true;
        }

        if (lblPaymentCash.Text == "1")
        {
            _paymentPDF.IsCash = true;
        }

        if (lblPaymentCreditCard.Text == "1")
        {
            _paymentPDF.IsCreditCard = true;
        }

        if (lblPaymentMaster.Text == "1")
        {
            _paymentPDF.IsMaster = true;
        }

        if (lblPaymentVisa.Text == "1")
        {
            _paymentPDF.IsVisa = true;
        }

        if (lblInstallment.Text == "1")
        {
            _paymentPDF.IsInstallment = true;
        }
        else
        {
            _paymentPDF.IsInstallment = false;
        }

        if (lblPaymentCheckNo.Text != string.Empty)
        {
            if (lblPaymentCheckNo.Text != "0")
            {
                _paymentPDF.IsCheckNo = true;
                _paymentPDF.CheckNo = lblPaymentCheckNo.Text;
            }
        }
        return _paymentPDF;
    }

    protected void btnBackToSearch_Click(object sender, EventArgs e)
    {
        btnSubmit_Click(sender, e);
    }

    private void CheckApplicationStatus()
    {
        MyDatabase _db = new MyDatabase();
        SortedList _paraList = new SortedList();
        _paraList.Add("@CECarID", lblCarID.Text);
        _paraList.Add("@CustomerID", lblCustomerID.Text);
        DataTable _dtApp = new DataTable("tblApp");
        _dtApp = _db.GetDataTableBySP("sprocCXCRMNonGGApplicationStatusSelectItem", _paraList);
        if (_dtApp != null && _dtApp.Rows.Count > 0)
        {
            lblAppType.Text = "NEW";
            if(_dtApp.Rows[0]["Info1"] != DBNull.Value && _dtApp.Rows[0]["Info1"].ToString() != string.Empty)
            {
                lblAppType.Text = _dtApp.Rows[0]["Info1"].ToString();
            }
            if (_dtApp.Rows[0]["PromotionCode"] != DBNull.Value && _dtApp.Rows[0]["PromotionCode"].ToString() != string.Empty)
            {
                string _Promo = _dtApp.Rows[0]["PromotionCode"].ToString();
                if (_Promo.ToString() == "1")
                {
                    divPromo.Visible = true;
                    lblPromotionType.Text = Resources.CarInsurance.Voucher200Baht;
                }
            }
            grvSelectedApp.DataSource = _dtApp;
            grvSelectedApp.DataBind();
        }
    }

    protected void btnSendPaymentReceipt_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session[General.UserRole].ToString() == "100")
            {
                btnSendPaymentReceipt.Enabled = false;
                btnPaymentReceiptDownload.Enabled = false;
                return;
            }

            Int16 IsThai = 1; //GetCustomerType(lblCustomerID.Text);
            if (chkSendPaymentEng.Checked) IsThai = 0;
            PaymentReceiptPDFOutput _payment = CreatePaymentPDFObject();
          
            string CurrentSession = string.Empty;
            if (Session["Language"] != null)
            {
                CurrentSession = System.Web.HttpContext.Current.Session["Language"].ToString();
            }
            if (IsThai == 1)
            {
                Session["Language"] = "th-TH";
            }
            else
            {
                Session["Language"] = "en-US";
            }
            String selectedCulture = CE.Global.General.SetCulture();
            base.InitializeCulture();           
            string _fileName = _payment.GeneratePDF(IsThai);
            if (CurrentSession.ToString() != string.Empty)
            {
                Session["Language"] = CurrentSession.ToString().Trim();
                selectedCulture = CE.Global.General.SetCulture();
                base.InitializeCulture(); 
            }
            if (_fileName != string.Empty)
            {
                FileInfo file = new System.IO.FileInfo(_fileName);
                BrokerPremiumDB _premiumDB = new BrokerPremiumDB();

                if (file.Exists)
                {
                    string[] _file = new string[1];
                    _file[0] = _fileName;

                    string _toemail = txtConfirmEmail.Text.Trim().ToLower();
                    string _ccemail = string.Empty;//Session[General.UserEmail].ToString();
                    string _bccemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
                    string _customerName = lblCustomerName.Text;
                    string imgUrl = "http://" + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
                    string _emailTitle = string.Empty;
                    string mailBody = "";
                    if (IsThai == 1)
                    {
                        _emailTitle = "เอกสารยืนยันการชำระค่าเบี้ยประกันภัย " + lblQuoteRefNo.Text;
                        mailBody = @"เรียน คุณ <strong>" + _customerName + "</strong><br/><br/>" +
                        "ขอบคุณที่ใช้บริการของเว็บไซต์ <a href='http://www.gluaygluay.com'>กล้วยๆ.com</a><br/>" +
                        "บริษัทฯขอนำส่งเอกสารยืนยันการชำระค่าเบี้ยประกันภัยให้ท่าน เพื่อเป็นหลักฐานในการสั่งซื้อ (โปรดดูไฟล์แนบ) <br/>" +
                        "ทั้งนี้ เอกสารใบเสร็จรับเงินตัวจริงจะถูกออกโดยบริษัทประกันฯ และจะส่งให้ท่านพร้อมกับเอกสารกรมธรรม์ต่อไป ขอบคุณค่ะ<br/>" +

                        "<br/>ขอแสดงความนับถือ<br/>" +
                        "<img src='" + imgUrl + "' alt='GluayGluay' width='120' height='100' /><br/>" +
                        "<br/><strong><a href='http://www.gluaygluay.com'>กล้วยๆ.com</a> Support Team</strong><br/>" +

                        "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด<br/>" +
                        "เลขทะเบียนนายหน้าประกันวินาศภัยนิติบุคคล เลขที่ ว00016/2553<br/>" +
                        "ชั้น 42 อาคารยูไนเต็ด เซ็นเตอร์<br/>" +
                        "เลขที่ 323 ถนนสีลม แขวงสีลม เขตบางรัก กรุงเทพฯ 10500<br/>" +
                        "โทร. 02-268-8222 โทรสาร 02-266-6339<br/>" +
                        "อีเมล์: support@gluaygluay.com<br/>" +
                        "กด Like เพื่อติดตามเราได้ใน Facebook: www.facebook.com/GGmotor";
                    }
                    else if (IsThai == 0)
                    {
                        _emailTitle = "Payment Confirmation Receipt " + lblQuoteRefNo.Text;
                        mailBody = @"Dear <strong>" + _customerName + "</strong><br/><br/>" +
                        "Thank you for using <a href='http://www.gluaygluay.com'>GluayGluay.com</a><br/>" +
                        "Please find enclosed in PDF the proof of premium payment.<br/>" +
                        "The original receipt will be issued by the insurance company and will be sent to you later together with the policy document.<br/>" +

                        "<br/>Yours truly,<br/>" +
                        "<img src='" + imgUrl + "' alt='GluayGluay' width='120' height='100' /><br/>" +
                        "<br/><strong><a href='http://www.gluaygluay.com'>Gluaygluay.com</a> Support Team</strong><br/>" +

                        "Comparexpress Insurance Broker ( Thailand ) Ltd,<br/>" +
                        "License number  ว00016/2553<br/>" +
                        "42nd Floor, United Center Building,<br/>" +
                        "323 Silom Road, Bangrak, Bangkok 10500<br/>" +
                        "Tel : 02-268-8222 , Fax : 02-266-6339" +
                        "Email : support@gluaygluay.com<br/>" +
                        "Please click like us to follow all activities at facebook : www.facebook.com/GGmotor";
                    }

                    bool _mailStatus = false;

                    _mailStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);

                    

                    if (_mailStatus)
                    {
                        if (_premiumDB.SaveQuotationEmail(Convert.ToInt32(lblCarID.Text),
                            Convert.ToInt64(lblCustomerID.Text),
                            Convert.ToInt64(Session[General.UserId].ToString()),
                            lblCarPlate.Text,
                            txtConfirmEmail.Text, 2, _fileName) > 0)
                        {
                            lblSendPaymentReceiptMessage.Text = "Sent to: " + txtConfirmEmail.Text + " on " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
                            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Sent successfully.\r\nSending Payment receipt transaction was SAVED');", true);
                        }
                        else
                        {
                            lblSendPaymentReceiptMessage.Text = "Sent successfully. Saving confirm email failed.";
                        }
                    }
                    else
                    {
                        lblSendPaymentReceiptMessage.Text = "Email sending failed.";
                    }
                }
                else
                {
                    lblSendPaymentReceiptMessage.Text = "PDF generating failed.";
                }
            }
            else
            {
                lblSendPaymentReceiptMessage.Text = "PDF generating failed. No item found.";
            }

        }
        catch (Exception Ex)
        {

            lblSendPaymentReceiptMessage.Text = Ex.Message;
        }
    }

    private void ShowLastQuotationSendDate()
    {
        if (lblCustomerID.Text != string.Empty && lblCarID.Text != string.Empty)
        {
            BrokerPremiumDB _db = new BrokerPremiumDB();
            Int64 CECarID = Convert.ToInt64(lblCarID.Text);
            Int64 CustomerID = Convert.ToInt64(lblCustomerID.Text);

            string _lastSendStatus = _db.GetLastQuotationSendDate(CECarID, CustomerID, 2);
            if (_lastSendStatus != string.Empty)
            {
                string[] strLastSendValues = _lastSendStatus.Split(',');
                lblSendPaymentReceiptMessage.Text = "Sent to : " + strLastSendValues[0];
                txtConfirmEmail.Text = strLastSendValues[0];

                lblSendPaymentReceiptMessage.Text += " on " + Convert.ToDateTime(strLastSendValues[1]).ToString("dd/MMM/yyyy hh:mm tt");
                //txtLicensePlate.ReadOnly = true;
            }
            else
            {
                lblSendPaymentReceiptMessage.Text = "Payment receipt email had NOT been sent.";
            }
        }
    }

    protected void grvPayment_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string _Approve = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ApproveType"));
            string _Refund = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Transaction"));
          
            if (_Approve == "1")
            {
                e.Row.Cells[8].ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                e.Row.Cells[8].ForeColor = System.Drawing.Color.Red;
            }

            if (_Refund.ToUpper() == "REFUND")
            {
                e.Row.Cells[8].ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                e.Row.Cells[8].ForeColor = System.Drawing.Color.Green;
            }
        }
    }

    private bool SendMailingStatusToCustomer()
    {
        bool _retValue = false;
        string MailRefNo = "";

        // *** Old ***
        //if (txtRemark.Text != string.Empty)
        //{
        //    MailRefNo = txtRemark.Text;
        //}
        // *** New ***
        if (txtTrackingNumber.Text != string.Empty)
        {
            MailRefNo = txtTrackingNumber.Text;
        }

        string _MSMailBody, _MSEmailTitle, _MSToEmail, _MSCCEmail, _MSBCCEmail, _MSviderName, ProviderBrokerCode;
        _MSMailBody = ""; _MSEmailTitle = ""; _MSToEmail = ""; _MSCCEmail = ""; _MSBCCEmail = "";
        _MSviderName = CE.Global.General.GetProviderName(Convert.ToInt64(lblProviderCompanyID.Text.Trim()));
        ProviderBrokerCode = CE.Global.General.GetProviderBrokerCode(Convert.ToInt64(lblProviderCompanyID.Text.Trim()));
        //string imgUrl = "http://" + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");

        string imgUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CRMPath") + "/";

        StringBuilder strMailBody = new StringBuilder();
        strMailBody.Append(@"<html>
                            <head>
                            <meta charset='utf-8'>
                            <title>GluayGluay</title>
                            <style>
                            body {
	                            margin-left: 0px;
	                            margin-top: 0px;
	                            margin-right: 0px;
	                            margin-bottom: 0px;
	                            font-family: tahoma, Arial, sans-serif;
	                            font-size: 14px;
	                            color: #4F4356 ;
	                            background-repeat: repeat-x;
	                            background-color: #fff;
	                            text-decoration: none;
                            }
                            a:link  {text-decoration:none; color:#0674DB;}
                            hr{display: block; height: 1px;
                                border: 0; border-top: 1px solid #ccc;
                                margin: 1em 0; padding: 0;}
	                            .line-height{line-height:20px;}
	                            .table-txt{padding-left:5px;}
                            </style>
                            </head><body>
                            <div class='email-containter'>
                            <div class='email-banner'></div>
                            <div class='email-text'>
                            <table width='800' border='0' align='center' cellpadding='0' cellspacing='0'>
                            <tr>
                            <td height='653' align='right' valign='bottom' bgcolor='#FFFFFF'>
                            <table width='800' height='100' border='0' cellspacing='0' cellpadding='0'>");
        strMailBody.Append("<tr><td><span class='email-banner'><img src='" + imgUrl + "images/email-header.jpg' width='800' height='100' alt=''/></span></td>");
        strMailBody.Append(@"</tr>
                            </table>
                            <table width='800' border='0' align='center' cellpadding='0' cellspacing='0'>
                            <tr>
                                <td width='672' align='left' valign='top' bgcolor='#FFFFFF'>
                            <table border='0' cellspacing='0' cellpadding='0'>
                            <tr>
                            <td align='left'>");
        _MSMailBody = strMailBody.ToString();
        if (!chkEmailEng.Checked)
        {
            _MSEmailTitle = "สถานะกรมธรรม์ของ ทะเบียนรถ [" + lblCarPlate.Text + "]";
            _MSMailBody += "<p>เรียน  " + lblCustomerName.Text + ",<br/></p>";
            _MSMailBody += "<p>อีเมลล์นี้เป็นการแจ้งให้ลูกค้าทราบว่า ทางบริษัทได้ดำเนินการเกี่ยวกับกรมธรรม์ของท่านเป็นที่เรียบร้อยแล้ว และได้ส่งให้ท่าน";
            _MSMailBody += "ทางไปรษณีย์ตามที่อยู่ที่ท่านได้ให้ไว้ โดยท่านสามารถตรวจสอบสถานะการจัดส่งที่ไปรษณีย์ไทย http://www.thailandpost.co.th/track.php ";
            _MSMailBody += "ด้วยตัวท่านเอง โดยใช้เลขที่ tracking (" + MailRefNo.ToString() + ")</p>";
            _MSMailBody += "<p>ถ้าหากท่านไม่ได้รับเอกสารกรมธรรม์ภายใน 7 วันทำการหลังจากได้รับอีเมลล์นี้ หรือถ้ามีข้อสงสัยประการใด กรุณาติดต่อเรา อีเมลล์ ";
            _MSMailBody += "support@gluaygluay.com หรือ โทรหาเราที่เบอร์ <strong>02-2688222</strong></p><br/>* รบกวนตรวจสอบหลังจากได้รับหมายเลข tracking 1 วัน<br/><br/>";

            _MSMailBody += "</td></tr><tr><td align=\"left\">";
            _MSMailBody += "ขอแสดงความนับถือ</td></tr></table><hr><p>" +
                                "<br/><strong><a href='http://www.gluaygluay.com'>GluayGluay.com</a>ฝ่ายประสานงาน GluayGluay</strong><br/>" +           
                                "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด<br/>" +
                                "เลขทะเบียนนายหน้าประกันวินาศภัยนิติบุคคล เลขที่ ว00016/2553<br/>" +
                                "42nd Floor, United Center Building,<br/>" +
                                "323 Silom Road, Bangrak, Bangkok 10500</p>" +
                                "<p>โทร. 02-268-8222 <br>โทรสาร 02-266-6339<br/>" +
                                "<a href=\"mailto:support@gluaygluay.com\">support@gluaygluay.com</a></p></td>" +
                                "</tr></table><hr>";
        }
        else
        {
            _MSEmailTitle = "Policy status for [" + lblCarPlate.Text + "]";
            _MSMailBody += "<p>Dear " + lblCustomerName.Text + ",<br/></p>";
            _MSMailBody += "<p>This email is to inform customer that our company have already completed submitting and issuing your policy, and already posting to you";
            _MSMailBody += "via thailandpost ,  and you can check the status of your policy by your self  via the website http://www.thailandpost.co.th/track.php ";
            _MSMailBody += "with the tracking reference (" + MailRefNo.ToString() + ")</p>";
            _MSMailBody += "<p>If you not receiving your policy within 7 days after receiving this email , or your have any inquiry please contact us email : ";
            _MSMailBody += "support@gluaygluay.com or call us at <strong>02-2688222</strong></p>";

            _MSMailBody += "</td></tr><tr><td align=\"left\">";
            _MSMailBody += "With best regards,</td></tr></table><hr><p>" +
            "<br/><strong><a href='http://www.gluaygluay.com'>Gluaygluay.com</a>Support Team</strong><br/>" +
            "Comparexpress Insurance Broker ( Thailand ) Ltd,<br/>" +
            "License number  ว00016/2553<br/>" +
            "42nd Floor, United Center Building,<br/>" +
            "323 Silom Road, Bangrak, Bangkok 10500</p>" +
            "<p>Tel : 02-268-8222 , Fax : 02-266-6339<br/>" +
            "<a href=\"mailto:support@gluaygluay.com\">support@gluaygluay.com</a></p></td>" +
            "</tr></table><hr>";
        }

        string YearEn = dateTimeNow.Year.ToString();
        strMailBody = new StringBuilder();
        strMailBody.Append(@"<table width='300' border='0' align='center' cellpadding='0' cellspacing='0'><tr>");
        strMailBody.Append("<td width='44' style='text-align: center'><a href='https://www.facebook.com/GGmotor'><img src='" + imgUrl + "images/icons/fb-big.png' width='44' height='42' alt=''/></a></td>");
        strMailBody.Append("<td width='44' style='text-align: center'><a href='https://plus.google.com/+Gluaygluay/posts'><img src='" + imgUrl + "images/icons/g-plus-big.png' width='44' height='42' alt=''/></a></td>");
        strMailBody.Append("<td width='44' style='text-align: center'><a href='https://www.youtube.com/channel/UCZ4gMtlXymBHxvcXO2cR1vA'><img src='" + imgUrl + "images/icons/youtube-big.png' width='44' height='42' alt=''/></a></td>");
        strMailBody.Append("<td width='44' style='text-align: center'><a href='http://iconosquare.com/ggmotor'><img src='" + imgUrl + "images/icons/instagram-big.png' width='44' height='42' alt=''/></a></td>");
        strMailBody.Append("<td width='43' style='text-align: center'><a href='https://www.linkedin.com/company/-com-gluaygluay-com-'><img src='" + imgUrl + "images/icons/linkedin-big.png' width='44' height='42' alt=''/></a></td>");
        strMailBody.Append(@"</tr>
                                         </table>
                                         <table width='800' height='100' border='0' cellspacing='0' cellpadding='0' background='images/email-footer.jpg'>
                                            <tr>
                                              <td><p style='text-align: center'><br><br>
                                                © " + YearEn + " gluaygluay.com. All rights reserved.<br>");
        strMailBody.Append(Resources.EmailMessage.NoReply);
        strMailBody.Append(@"</p></td></tr>
                                          </table></td>
                                          </tr>
                                        </table>
                                        </body>
                                        </html>");
        _MSMailBody += strMailBody.ToString();

        _MSToEmail = txtCustEmail.Text;
        _MSCCEmail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("SUPPORT");

        _retValue = MyMailManager.SendGGMail(ConfigurationManager.AppSettings["GGServiceSMTPAccount"].ToString(), ConfigurationManager.AppSettings["GGServiceSMTPAuthCode"].ToString(), _MSToEmail, _MSCCEmail, _MSBCCEmail, _MSEmailTitle, _MSMailBody, Session[General.SMTPReplyTo].ToString());

        return _retValue;
    }

    private void GetCustomerEmail()
    {
        if (lblCarID.Text != string.Empty && lblCustomerID.Text != string.Empty)
        {
            MyDatabase _myDb = new MyDatabase("GG_CRMDBConnectionString");
            DataTable _dtLanguage = new DataTable("tblLanguage");
            _dtLanguage = _myDb.GetDataTable(@"SELECT Info2 FROM tblNonGGTransaction WHERE TransactionTypeId = 400 AND RefCEUserId = " + lblCustomerID.Text + " AND CECarId = " + lblCarID.Text);
            if (_dtLanguage != null && _dtLanguage.Rows.Count > 0)
            {
                if (_dtLanguage.Rows[0]["Info2"] != DBNull.Value && _dtLanguage.Rows[0]["Info2"].ToString() != string.Empty)
                {
                    txtCustEmail.Text = _dtLanguage.Rows[0]["Info2"].ToString();
                }
                else
                {
                    txtCustEmail.Text = txtConfirmEmail.Text;
                }
            }
            else
            {
                txtCustEmail.Text = txtConfirmEmail.Text;
            }
        }
    }

    public Int16 GetCustomerType(string RefCEUserId)
    {
        Int16 IsThai = 1;
        MyDatabase _db = new MyDatabase();
        string strSql = "SELECT IsThai = CASE WHEN Ninfo7 IS NULL THEN 1 ELSE Ninfo7 END FROM tblCEUsrProfile WHERE RefCEUserId = " + RefCEUserId;
        object _result = _db.ExecuteScalarSqlStatement(strSql);
        if (_result != null)
        {
            if (!Int16.TryParse(_result.ToString(), out IsThai))
            {
                IsThai = 1;
            }
        }
        return IsThai;
    }

   
    private void GetEmailLanguage()
    {
        if (lblCustomerID.Text != string.Empty)
        {
            MyDatabase _myDb = new MyDatabase("GG_CRMDBConnectionString");
            Object custLang = _myDb.ExecuteScalarSqlStatement(@"SELECT IsEnglish FROM tblCarDetailTH WHERE RefCEUserId = " + lblCustomerID.Text);
            if (custLang != null)
            {
                if (custLang.ToString() == "1")
                {
                    chkEmailEng.Checked = true;
                }
            }
        }
    }

    #region Not Using - 10 Jul 2012

    private string GetProviderName(Int64 ProviderCompanyId)
    {
        string _result = "";
        if (ProviderCompanyId == 11)
        {
            _result = "อลิอันซ์ ซี.พี. ประกันภัย";
        }
        else if (ProviderCompanyId == 12)
        {
            _result = "เอ็ม เอส ไอ จี ประกันภัย";
        }
        else if (ProviderCompanyId == 16)
        {
            _result = "แอกซ่า ประกันภัย";
        }
        else if (ProviderCompanyId == 29)
        {
            _result = "แอลเอ็มจี ประกันภัย";
        }
        else if (ProviderCompanyId == 31)
        {
            _result = "นิวแฮมพ์เชอร์ อินชัวรันส์";
        }
        else if (ProviderCompanyId == 32)
        {
            _result = "กรุงเทพประกันภัย";
        }
        else if (ProviderCompanyId == 33)
        {
            _result = "เมืองไทยประกันภัย";
        }
        else if (ProviderCompanyId == 35)
        {
            _result = "บริษัท กรุงไทยพานิชประกันภัย";
        }
        else if (ProviderCompanyId == 41)
        {
            _result = "คูเนีย ประกันภัย";
        }
        else if (ProviderCompanyId == 46)
        {
            _result = "โตเกียวมารีนศรีเมือง";
        }
        return _result;
    }

    private string GetProviderName(Int64 ProviderCompanyId, string Language)
    {
        string _result = "";
        if (Language == "1")
        {
            if (ProviderCompanyId == 11)
            {
                _result = "อลิอันซ์ ซี.พี. ประกันภัย";
            }
            else if (ProviderCompanyId == 12)
            {
                _result = "เอ็ม เอส ไอ จี ประกันภัย";
            }
            else if (ProviderCompanyId == 16)
            {
                _result = "แอกซ่า ประกันภัย";
            }
            else if (ProviderCompanyId == 29)
            {
                _result = "แอลเอ็มจี ประกันภัย";
            }
            else if (ProviderCompanyId == 31)
            {
                _result = "นิวแฮมพ์เชอร์ อินชัวรันส์";
            }
            else if (ProviderCompanyId == 32)
            {
                _result = "กรุงเทพประกันภัย";
            }
            else if (ProviderCompanyId == 33)
            {
                _result = "เมืองไทยประกันภัย";
            }
            else if (ProviderCompanyId == 35)
            {
                _result = "บริษัท กรุงไทยพานิชประกันภัย";
            }
            else if (ProviderCompanyId == 41)
            {
                _result = "คูเนีย ประกันภัย";
            }
            else if (ProviderCompanyId == 46)
            {
                _result = "โตเกียวมารีนศรีเมือง";
            }
        }
        else if (Language == "2")
        {
            if (ProviderCompanyId == 11)
            {
                _result = "Allianz CP Insurance";
            }
            else if (ProviderCompanyId == 12)
            {
                _result = "MSIG Insurance";
            }
            else if (ProviderCompanyId == 16)
            {
                _result = "AXA Insurance";
            }
            else if (ProviderCompanyId == 29)
            {
                _result = "LMG  Insurance";
            }
            else if (ProviderCompanyId == 31)
            {
                _result = "Chartis Insurance";
            }
            else if (ProviderCompanyId == 32)
            {
                _result = "BKI Insurance";
            }
            else if (ProviderCompanyId == 33)
            {
                _result = "MuangThai Insurance";
            }
            else if (ProviderCompanyId == 35)
            {
                _result = "Krungthai Panich Insurance";
            }
            else if (ProviderCompanyId == 41)
            {
                _result = "Kurnia Insurance";
            }
            else if (ProviderCompanyId == 46)
            {
                _result = "Tokio Marine Insurance";
            }
        }
        return _result;
    }

    private string GetProviderBrokerCode(Int64 ProviderCompanyId)
    {
        string _result = "";
        if (ProviderCompanyId == 11)
        {
            _result = "001600";
        }
        else if (ProviderCompanyId == 12)
        {
            _result = "AFM1012";
        }
        else if (ProviderCompanyId == 16)
        {
            _result = "BB115";
        }
        else if (ProviderCompanyId == 29)
        {
            _result = "BR00619";
        }
        else if (ProviderCompanyId == 31)
        {
            _result = "002851000";
        }
        else if (ProviderCompanyId == 32)
        {
            _result = "641100";
        }
        else if (ProviderCompanyId == 33)
        {
            _result = "74000352";
        }
        else if (ProviderCompanyId == 41)
        {
            _result = "198700-00";
        }
        else if (ProviderCompanyId == 46)
        {
            _result = "10233002";
        }
        return _result;
    }

    private string GetProviderMail(Int64 ProviderCompanyId)
    {
        string _result = "";
        if (ProviderCompanyId == 11)
        {
            _result = "TO_AZCP";
        }
        else if (ProviderCompanyId == 12)
        {
            _result = "TO_MSIG";
        }
        else if (ProviderCompanyId == 16)
        {
            _result = "TO_AXA";
        }
        else if (ProviderCompanyId == 29)
        {
            _result = "TO_LMG";
        }
        else if (ProviderCompanyId == 31)
        {
            _result = "TO_CTS";
        }
        else if (ProviderCompanyId == 32)
        {
            _result = "TO_BKI";
        }
        else if (ProviderCompanyId == 33)
        {
            _result = "TO_MTI";
        }
        else if (ProviderCompanyId == 35)
        {
            _result = "TO_KPI";
        }
        else if (ProviderCompanyId == 41)
        {
            _result = "TO_KUR";
        }
        else if (ProviderCompanyId == 46)
        {
            _result = "TO_TMS";
        }
        return _result;
    }

    #endregion

}
